<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\BaseController;
use App\Services\Tools\CommonService;
use App\Services\Tools\ExportService;
use Illuminate\Http\Request;    //引用http请求类
use App\Exceptions\BasicException;  //引入框架异常处理类
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;    //引入hash
use App\Services\Cache\AdminCacheService;   //admin缓存
use App\Services\Tools\JwtService;    //引入JWT服务
use App\Services\Tools\FileService;   //引入文件处理类
use App\Response\Response;
use App\Models\MainDB\GiveGiftDay;
use Illuminate\Support\Facades\Redis;
use Monolog\Handler\IFTTTHandler;

class BossController extends BaseController {

    public $type, $pot_name;

    public function __construct(Request $request) {
        $this->type = $request->input('type', 3);
        switch ($this->type) {
            case 1:
                $this->pot_name = '1连奖池';
                break;
            case 2:
                $this->pot_name = '10连奖池';
                break;
            case 3:
                $this->pot_name = '100连奖池';
                break;
            case 4:
                $this->pot_name = '特殊奖池';
                break;
            default:
                $this->pot_name = '100连奖池';
        }
    }

    /**
     * @api {post} /boss/set_boss  设置新的boss
     * @apiVersion 0.1.0
     * @apiName 设置新的boss
     * @apiGroup 游戏管理
     * @apiParam {string} start_time  活动开始时间，必传
     * @apiParam {string} end_time  活动结束时间，必传
     * @apiParam {number} start_time_slot  活动开始时间段，必传
     * @apiParam {number} end_time_slot  活动结束时间段，必传
     * @apiParam {number} lowest_blood  最低血量，必传
     * @apiParam {number} highest_blood  最高血量，必传
     * @apiParam {number} refresh_seconds  boss刷新秒数，必传
     * @apiParam {string} attack_price  攻击boss的价格，非必传
     *
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": true
     * }
     */
    public  function  setBoss(Request $request){
        //参数校验
        $v = app('validator')->make(
            $request->all(),
            [
                'start_time' => 'required|date_format:"Y-m-d"',
                'end_time' => 'required|date_format:"Y-m-d"',
                'start_time_slot' => 'required|numeric|between:0,24',
                'end_time_slot' => 'required|numeric|between:0,24|gt:start_time_slot',
                'lowest_blood' => 'required|numeric',
                'highest_blood' => 'required|numeric|gt:lowest_blood',
                'refresh_seconds' => 'required|numeric',
                'attack_price' => 'filled|numeric',
            ]
        );

        if ($v->fails()) throw new BasicException(10001);
         $param = $request->only(['start_time','end_time','start_time_slot','end_time_slot','lowest_blood','highest_blood','refresh_seconds']);
         $attack_price = $request->input('attack_price',1);
         $start_time = strtotime($param['start_time']);
         $end_time =  strtotime($param['end_time'].' 23:59:59');
         $param['start_time']=$start_time;
         $param['end_time']=$end_time;
         $param['attack_price']=$attack_price;
         $param['add_time'] =time();
         $param['left_blood'] =0;
         $param['total_blood'] =0;
         $param['is_attack_boss'] =2;
         $param['award_num'] =0;
         app('repo_virus_boss')->setBoss($param);
         return Response::sendData(true);
    }

    /**
     * @api {post} /boss/get_boss_detail  获取boss详情
     * @apiVersion 0.1.0
     * @apiName 获取boss详情
     * @apiGroup 游戏管理
     * @apiSuccessExample 成功响应
        {
            "code": 200,
            "data": {
                "start_time(开始时间)": "2020-07-17",
                "end_time（结束时间）": "2020-12-17",
                "start_time_slot（开始时间段）": "0",
                "end_time_slot（结束时间段）": "24",
                "refresh_seconds（boss刷新秒数）": 10,
                "attack_price（攻击boss价格）": "1",
                "lowest_blood（最低血量）": "5000",
                "highest_blood（最高血量）": "6000"
            }
        }
     */
    public function  getBossDetail(){
        $boss_detail=app('repo_virus_boss')->getBossDetail();
        $boss_detail['start_time'] =date('Y-m-d',$boss_detail['start_time'] ?? 0);
        $boss_detail['end_time'] =date('Y-m-d',$boss_detail['end_time'] ?? 0);
        return Response::sendData($boss_detail);
    }

    /**
     * @api {post} /boss/get_this_prize_list  boss获取本期奖池列表
     * @apiVersion 0.1.0
     * @apiName boss获取本期奖池列表
     * @apiGroup 游戏管理
     * @apiParam {number} type  1一连 2十连 3百连 4特殊奖池，必传
     * @apiSuccessExample 成功响应
         {
        "code": 200,
        "data": {
                "pool_type（当前抽奖类型:1数量奖池 2概率奖池）": "1",
                "pool_type_name（当前抽奖类型）": "当前为数量奖池",
                "pot_name(奖池名称)": "100连奖池",
                "type（奖池类型）": "3",
                "total_count（奖品总数）": 99900,
                "total_money（金币总数）": 28822753,
                "list（礼物列表）": [
                    {
                    "id（主键id）": 122,
                    "gift_id（礼物id）": 161,
                    "number（礼物数量）": 5,
                    "ratio（爆率）": 0,
                    "percent（百分比）": 0,
                    "gift_name（奖品名字）": "公主の梦",
                    "price（价格）": 520000,
                    "picture（图片）": "http://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/admin_images/5e63d1528eb2e.png",
                    "special（动效）": "http://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/admin_images/5e63d1584d2cb.svga",
                    "gift_rank（奖品等级颜色）": "橙色"
                    }
                ]
            }
        }
     */
    public  function  getThisPrizeList(Request $request){
        //参数校验
        $v = app('validator')->make(
            $request->all(),
            [
                'type' => 'required|in:1,2,3,4',
            ]
        );
        if ($v->fails()) throw new BasicException(10001);
        $type = $request->input('type');
        $list=app('repo_virus_this_prize')->getThisPrizeList($type);
        //获取奖品总数量
        $total_count =0;
        //获取奖品总金币数量
        $total_money = 0;
        if ($list){
             foreach ($list as $key=>&$value){
                 $value['gift_name']=$value['gift']['name'];
                 $value['price']=$value['gift']['price'];
                 $value['picture']=$value['gift']['picture'];
                 $value['special']=$value['gift']['special'];
                 $value['gift_rank']=CommonService::giftRank($value['gift']['price']);
                 $total_count +=$value['number'];
                 $total_money+=($value['number']*$value['gift']['price']);
                 unset($value['gift']);
             }
        }
        $pool_type= app('repo_config')->queryConfig('BONUS_POOL_TYPE');
        if ($pool_type->value==1){
            $pool_type_name ='当前为数量奖池';
        }else{
            $pool_type_name ='当前为概率奖池';
        }
        $data =[
            'pool_type'=>$pool_type->value,
            'pool_type_name'=>$pool_type_name,
            'pot_name'=>$this->pot_name,
            'type'=>$type,
            'total_count'=>$total_count,
            'total_money'=>$total_money,
            'list'=>$list,
        ];
        return Response::sendData($data);
    }



    /**
     * @api {post} /boss/get_next_prize_list  boss获取下期奖池列表
     * @apiVersion 0.1.0
     * @apiName boss获取下期奖池列表
     * @apiGroup 游戏管理
     * @apiParam {number} type  1一连 2十连 3百连 4特殊奖池，必传
     * @apiSuccessExample 成功响应
        {
            "code": 200,
            "data": {
                "pot_name(奖池名称)": "100连奖池",
                "type（奖池类型）": "3",
                "list（礼物列表）": [
                    {
                    "id（主键id）": 122,
                    "gift_id（礼物id）": 161,
                    "number（礼物数量）": 5,
                    "ratio（爆率）": 0,
                    "percent（百分比）": 0,
                    "gift_name（奖品名字）": "公主の梦",
                    "price（价格）": 520000,
                    "picture（图片）": "http://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/admin_images/5e63d1528eb2e.png",
                    "special（动效）": "http://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/admin_images/5e63d1584d2cb.svga",
                    "gift_rank（奖品等级颜色）": "橙色"
                    }
                ]
            }
        }
     */
    public  function  getNextPrizeList(Request $request){
        //参数校验
        $v = app('validator')->make(
            $request->all(),
            [
                'type' => 'required|in:1,2,3,4',
            ]
        );
        if ($v->fails()) throw new BasicException(10001);
        $type = $request->input('type');
        $list=app('repo_virus_next_prize')->getNextPrizeList($type);
        if ($list){
            foreach ($list as $key=>&$value){
                $value['gift_name']=$value['gift']['name'];
                $value['price']=$value['gift']['price'];
                $value['picture']=$value['gift']['picture'];
                $value['special']=$value['gift']['special'];
                $value['gift_rank']=CommonService::giftRank($value['gift']['price']);
                unset($value['gift']);
            }
        }
        $data =[
            'pot_name'=>$this->pot_name,
            'type'=>$type,
            'list'=>$list,
        ];
        return Response::sendData($data);
    }



    /**
     * @api {post} /boss/get_gift_list  boss获取编辑、新增奖品列表
     * @apiVersion 0.1.0
     * @apiName boss获取编辑、新增奖品列表
     * @apiGroup 游戏管理
     * @apiSuccessExample 成功响应
        {
            "code": 200,
            "data": [
                {
                "id(礼物主键)": 229,
                "name（名字）": "47",
                "price（价格）": 10,
                "picture（图片）": "http://yutangyuyin1.oss-cn-hangzhou.aliyuncs.com/admin_images/5ef3383561bb2.png"
                }
            ]
        }
     */
    public function  getGiftList(){
        $gifts = app('repo_gift')->gameGiftList(6);
        return Response::sendData($gifts);
    }


    /**
     * @api {post} /boss/add_boss_this_gift  boss新增本期奖池礼物
     * @apiVersion 0.1.0
     * @apiName boss新增本期奖池礼物
     * @apiGroup 游戏管理
     * @apiParam {number} type  1一连 2十连 3百连 4特殊奖池，必传
     * @apiParam {number} number  奖品数量，必传
     * @apiParam {number} gift_id  奖品数量，必传
     * @apiParam {string} percent  获奖的百分比，非必传
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": true
     * }
     */

    public function add_boss_this_gift(Request $request){
        //参数校验
        $v = app('validator')->make(
            $request->all(),
            [
                'type' => 'required|in:1,2,3,4',
                'number' => 'required|numeric',
                'gift_id' => 'required|numeric',
                'percent' => 'filled',
            ]
        );
        if ($v->fails()) throw new BasicException(10001);
        $param = $request->only(['type','number','gift_id']);
        $percent = $request->input('percent',1);
        $param['percent'] =$percent;
        app('repo_virus_this_prize')->verifyGift($param['type'],$param['gift_id'],$percent);
        app('repo_virus_this_prize')->addGift($param);
        return Response::sendData(true);
    }

    /**
     * @api {post} /boss/add_boss_next_gift  boss新增下期奖池礼物
     * @apiVersion 0.1.0
     * @apiName boss新增下期奖池礼物
     * @apiGroup 游戏管理
     * @apiParam {number} type  1一连 2十连 3百连 4特殊奖池，必传
     * @apiParam {number} number  奖品数量，必传
     * @apiParam {number} gift_id  奖品数量，必传
     * @apiParam {string} percent  获奖的百分比，非必传
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": true
     * }
     */

    public function add_boss_next_gift(Request $request){
        //参数校验
        $v = app('validator')->make(
            $request->all(),
            [
                'type' => 'required|in:1,2,3,4',
                'number' => 'required|numeric',
                'gift_id' => 'required|numeric',
                'percent' => 'filled',
            ]
        );
        if ($v->fails()) throw new BasicException(10001);
        $param = $request->only(['type','number','gift_id']);
        $percent = $request->input('percent',1);
        $param['percent'] =$percent;
        app('repo_virus_next_prize')->verifyGift($param['type'],$param['gift_id'],$percent);
        app('repo_virus_next_prize')->addGift($param);
        return Response::sendData(true);
    }


    /**
     * @api {post} /boss/add_chance_gift  概率奖池新增礼物
     * @apiVersion 0.1.0
     * @apiName 概率奖池新增礼物
     * @apiGroup 游戏管理
     * @apiParam {number} type  1一连 2十连 3百连 4特殊奖池，必传
     * @apiParam {number} gift_id  奖品数量，必传
     * @apiParam {number} initial_weight  初始权重，必传
     * @apiParam {string} percent  获奖的百分比，非必传
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": true
     * }
     */

    public function add_chance_gift(Request $request){
        //参数校验
        $v = app('validator')->make(
            $request->all(),
            [
                'type' => 'required|in:1,2,3,4',
                'gift_id' => 'required|numeric',
                'initial_weight' => 'required|numeric',
                'percent' => 'filled',
            ]
        );
        if ($v->fails()) throw new BasicException(10001);
        $param = $request->only(['type','gift_id','initial_weight']);
        if ($param['type'] ==4){
            $percent = $request->input('percent',1);
        }else{
            $percent =1;
        }
        $param['percent'] =$percent;
        app('repo_virus_chance_prize')->verifyGift($param['type'],$param['gift_id'],$percent);
        app('repo_virus_chance_prize')->addGift($param);

        Redis::del('boss_filter_big_gifts'.$this->type);
        Redis::del('boss_filter_small_gifts'.$this->type);
        Redis::del('boss_chance_gifts'.$this->type);
        Redis::del('total_initial_weight'.$this->type);
        Redis::del('default_input_value'.$this->type);
        Redis::del('preset_output_value'.$this->type);
        Redis::del('boss_filter_big_gifts'.$this->type);
        Redis::del('boss_filter_big_gifts40.25');
        Redis::del('boss_filter_big_gifts40.5');
        Redis::del('boss_filter_big_gifts40.75');
        Redis::del('boss_filter_big_gifts40');
        return Response::sendData(true);
    }



    /**
     * @api {post} /boss/save_boss_this_gift  boss编辑本期奖池礼物
     * @apiVersion 0.1.0
     * @apiName boss编辑本期奖池礼物
     * @apiGroup 游戏管理
     * @apiParam {number} id  主键id，必传
     * @apiParam {number} type  1一连 2十连 3百连 4特殊奖池，必传
     * @apiParam {number} number  奖品数量，必传
     * @apiParam {number} gift_id  奖品数量，必传
     * @apiParam {string} percent  获奖的百分比，非必传
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": true
     * }
     */

    public function  save_boss_this_gift(Request $request){
        //参数校验
        $v = app('validator')->make(
            $request->all(),
            [
                'id' => 'required|numeric',
                'type' => 'required|in:1,2,3,4',
                'number' => 'required|numeric',
                'gift_id' => 'required|numeric',
                'percent' => 'filled',
            ]
        );
        if ($v->fails()) throw new BasicException(10001);
        $param = $request->only(['id','type','number','gift_id']);
        $percent = $request->input('percent',1);
        $param['percent'] =$percent;
        app('repo_virus_this_prize')->verifyGift($param['type'],$param['gift_id'],$percent);
        app('repo_virus_this_prize')->saveGift($param);
        return Response::sendData(true);
    }

    /**
     * @api {post} /boss/save_boss_next_gift  boss编辑下期奖池礼物
     * @apiVersion 0.1.0
     * @apiName boss编辑下期奖池礼物
     * @apiGroup 游戏管理
     * @apiParam {number} id  主键id，必传
     * @apiParam {number} type  1一连 2十连 3百连 4特殊奖池，必传
     * @apiParam {number} number  奖品数量，必传
     * @apiParam {number} gift_id  奖品数量，必传
     * @apiParam {string} percent  获奖的百分比，非必传
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": true
     * }
     */

    public function  save_boss_next_gift(Request $request){
        //参数校验
        $v = app('validator')->make(
            $request->all(),
            [
                'id' => 'required|numeric',
                'type' => 'required|in:1,2,3,4',
                'number' => 'required|numeric',
                'gift_id' => 'required|numeric',
                'percent' => 'filled',
            ]
        );
        if ($v->fails()) throw new BasicException(10001);
        $param = $request->only(['id','type','number','gift_id']);
        $percent = $request->input('percent',1);
        $param['percent'] =$percent;
        app('repo_virus_next_prize')->verifyGift($param['type'],$param['gift_id'],$percent);
        app('repo_virus_next_prize')->saveGift($param);
        return Response::sendData(true);
    }

    /**
     * @api {post} /boss/save_chance_gift  编辑概率奖池
     * @apiVersion 0.1.0
     * @apiName 编辑概率奖池
     * @apiGroup 游戏管理
     * @apiParam {number} id  主键id，必传
     *@apiParam {number} type  1一连 2十连 3百连 4特殊奖池，必传
     * @apiParam {number} initial_weight  初始权重，必传
     * @apiParam {number} gift_id  奖品数量，必传
     * @apiParam {string} percent  获奖的百分比，非必传
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": true
     * }
     */
    public function  save_chance_gift(Request $request){
        //参数校验
        $v = app('validator')->make(
            $request->all(),
            [
                'id' => 'required|numeric',
                'gift_id' => 'required|numeric',
                'initial_weight' => 'required|numeric',
                'type' => 'required|in:1,2,3,4',
                'percent' => 'filled',
            ]
        );
        if ($v->fails()) throw new BasicException(10001);
        $param = $request->only(['id','initial_weight','gift_id','type']);
        $percent = $request->input('percent',1);
        $param['percent'] =$percent;
        app('repo_virus_chance_prize')->verifyGift($param['type'],$param['gift_id'],$percent);
        app('repo_virus_chance_prize')->saveGift($param);
        Redis::del('boss_filter_big_gifts'.$this->type);
        Redis::del('boss_filter_small_gifts'.$this->type);
        Redis::del('boss_chance_gifts'.$this->type);
        Redis::del('total_initial_weight'.$this->type);
        Redis::del('default_input_value'.$this->type);
        Redis::del('preset_output_value'.$this->type);
        Redis::del('boss_filter_big_gifts'.$this->type);
        Redis::del('boss_filter_big_gifts40.25');
        Redis::del('boss_filter_big_gifts40.5');
        Redis::del('boss_filter_big_gifts40.75');
        Redis::del('boss_filter_big_gifts40');
        return Response::sendData(true);
    }


    /**
     * @api {post} /boss/del_boss_this_gift  boss删除本期奖池礼物
     * @apiVersion 0.1.0
     * @apiName boss删除本期奖池礼物
     * @apiGroup 游戏管理
     * @apiParam {string} ids 主键（多个用逗号隔开），必传

     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": true
     * }
     * @apiError 93090  boss本期奖池删除失败
     * @apiErrorExample 错误响应
     *
     *      {
     *          "code": 93090,
     *          "message": "errorMsg"
     *      }
     */
    public  function  del_boss_this_gift(Request $request){
        //参数校验
        $v = app('validator')->make(
            $request->all(),
            [
                'ids' => 'required',
            ]
        );
        if ($v->fails()) throw new BasicException(10001);
        $ids = $request->input('ids');
        $arr_ids = explode(',', $ids);
        app('repo_virus_this_prize')->delThisPrize($arr_ids);
        return Response::sendData(true);
    }


    /**
     * @api {post} /boss/del_boss_next_gift  boss删除下期奖池礼物
     * @apiVersion 0.1.0
     * @apiName boss删除下期奖池礼物
     * @apiGroup 游戏管理
     * @apiParam {string} ids 主键（多个用逗号隔开），必传
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": true
     * }
     * @apiError 93095  boss下期奖池删除失败
     * @apiErrorExample 错误响应
     *      {
     *          "code": 93095,
     *          "message": "errorMsg"
     *      }
     */
    public  function  del_boss_next_gift(Request $request){
        //参数校验
        $v = app('validator')->make(
            $request->all(),
            [
                'ids' => 'required',
            ]
        );
        if ($v->fails()) throw new BasicException(10001);
        $ids = $request->input('ids');
        $arr_ids = explode(',', $ids);
        app('repo_virus_next_prize')->delNextPrize($arr_ids);
        return Response::sendData(true);
    }

    /**
     * @api {post} /boss/del_chance_gift  删除概率奖池礼物
     * @apiVersion 0.1.0
     * @apiName 删除概率奖池礼物
     * @apiGroup 游戏管理
     * @apiParam {string} ids 主键（多个用逗号隔开），必传
     * @apiParam {string} type  类型：1一连 2十连 3 百连 4特殊，必传
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": true
     * }
     * @apiError 93095  删除概率奖池失败
     * @apiErrorExample 错误响应
     *      {
     *          "code": 93095,
     *          "message": "errorMsg"
     *      }
     */
    public  function  del_chance_gift(Request $request){
        //参数校验
        $v = app('validator')->make(
            $request->all(),
            [
                'ids' => 'required',
                'type' => 'required|in:1,2,3,4',
            ]
        );
        if ($v->fails()) throw new BasicException(10001);
        $ids = $request->input('ids');
        $arr_ids = explode(',', $ids);
        app('repo_virus_chance_prize')->delChancePrize($arr_ids);
        Redis::del('boss_filter_big_gifts'.$this->type);
        Redis::del('boss_filter_small_gifts'.$this->type);
        Redis::del('boss_chance_gifts'.$this->type);
        Redis::del('total_initial_weight'.$this->type);
        Redis::del('default_input_value'.$this->type);
        Redis::del('preset_output_value'.$this->type);
        Redis::del('boss_filter_big_gifts'.$this->type);
        Redis::del('boss_filter_big_gifts40.25');
        Redis::del('boss_filter_big_gifts40.5');
        Redis::del('boss_filter_big_gifts40.75');
        Redis::del('boss_filter_big_gifts40');
        return Response::sendData(true);
    }

    /**
     * @api {post} /boss/edit_all_this_list  boss一键修改本期奖池列表
     * @apiVersion 0.1.0
     * @apiName boss一键修改本期奖池列表
     * @apiGroup 游戏管理
     * @apiParam {number} type  奖池类型：1一连 2十连 3百连 4特殊奖池，必传
     * @apiSuccessExample 成功响应
        {
            "code": 200,
            "data": {
                "type(奖池类型)": "3",
                "pot_name（奖池名称）": "100连奖池",
                "list（礼物列表）": [
                    {
                    "id（主键id）": 122,
                    "gift_id（礼物id）": 161,
                    "number（礼物数量）": 5,
                    "gift_name（礼物名字）": "公主の梦"
                    }
                ]
            }
        }
     */
    public function  edit_all_this_list(Request $request){
        //参数校验
        $v = app('validator')->make(
            $request->all(),
            [
                'type' => 'required|in:1,2,3,4',
            ]
        );
        if ($v->fails()) throw new BasicException(10001);
        $type = $request->input('type');
        $list = app('repo_virus_this_prize')->getThisPrizeList($type);
        if ($list){
            foreach ($list as $key=>&$value){
                $value['gift_name'] =$value['gift']['name'];
                unset($value['gift']);
                unset($value['ratio']);
                unset($value['percent']);
            }
        }
        $data =[
            'type'=>$type,
            'pot_name'=>$this->pot_name,
            'list'=>$list,
        ];
        return Response::sendData($data);
    }


    /**
     * @api {post} /boss/edit_all_next_list  boss一键修改下期奖池列表
     * @apiVersion 0.1.0
     * @apiName boss一键修改下期奖池列表
     * @apiGroup 游戏管理
     * @apiParam {number} type  奖池类型：1一连 2十连 3百连 4特殊奖池，必传
     * @apiSuccessExample 成功响应
        {
            "code": 200,
            "data": {
                "type(奖池类型)": "3",
                "pot_name（奖池名称）": "100连奖池",
                "list（礼物列表）": [
                    {
                    "id（主键id）": 122,
                    "gift_id（礼物id）": 161,
                    "number（礼物数量）": 5,
                    "gift_name（礼物名字）": "公主の梦"
                    }
                ]
            }
        }
     */
    public function  edit_all_next_list(Request $request){
        //参数校验
        $v = app('validator')->make(
            $request->all(),
            [
                'type' => 'required|in:1,2,3,4',
            ]
        );
        if ($v->fails()) throw new BasicException(10001);
        $type = $request->input('type');
        $list = app('repo_virus_next_prize')->getNextPrizeList($type);
        if ($list){
            foreach ($list as $key=>&$value){
                $value['gift_name'] =$value['gift']['name'];
                unset($value['gift']);
                unset($value['ratio']);
                unset($value['percent']);
            }
        }
        $data =[
            'type'=>$type,
            'pot_name'=>$this->pot_name,
            'list'=>$list,
        ];
        return Response::sendData($data);
    }


    /**
     * @api {post} /boss/do_edit_all_this    boss一键修改本期奖池
     * @apiVersion 0.1.0
     * @apiName boss一键修改本期奖池
     * @apiGroup 游戏管理
     * @apiParam {array} list  礼物列表，必传
     * @apiSuccessExample 成功响应
     * { "code": 200, "data": true }
     */
    public function  do_edit_all_this(Request $request){
        //参数校验
        $v = app('validator')->make(
            $request->all(),
            [
                'list' => 'required|array',
            ]
        );
        if ($v->fails()) throw new BasicException(10001);
        $list = $request->input('list');
        if ($list){
            foreach ($list as $key=>$val){
                app('repo_virus_this_prize')->editAllGifts($val);
            }
        }
        return Response::sendData(true);
    }


    /**
     * @api {post} /boss/do_edit_all_next    boss一键修改下期奖池
     * @apiVersion 0.1.0
     * @apiName boss一键修改下期奖池
     * @apiGroup 游戏管理
     * @apiParam {array} list  礼物列表，必传
     * @apiSuccessExample 成功响应
     * { "code": 200, "data": true }
     */
    public function  do_edit_all_next(Request $request){
        //参数校验
        $v = app('validator')->make(
            $request->all(),
            [
                'list' => 'required|array',
            ]
        );
        if ($v->fails()) throw new BasicException(10001);
        $list = $request->input('list');
        if ($list){
            foreach ($list as $key=>$val){
                app('repo_virus_next_prize')->editAllGifts($val);
            }
        }
        return Response::sendData(true);
    }

    /**
     * @api {post} /boss/boss_this_set_number    boss本期奖池设为数量奖池
     * @apiVersion 0.1.0
     * @apiName boss本期奖池设为数量奖池
     * @apiGroup 游戏管理
     * @apiSuccessExample 成功响应
     * { "code": 200, "data": true }
     */
    public  function  boss_this_set_number(Request $request){
        $where[] =['key','BONUS_POOL_TYPE'];
        $param =[
            'value'=>1
        ];
        app('repo_config')->saveConfig($where,$param);
        return Response::sendData(true);
    }

    /**
     * @api {post} /boss/open_chance_gift    开启概率奖池
     * @apiVersion 0.1.0
     * @apiName 开启概率奖池
     * @apiGroup 游戏管理
     * @apiSuccessExample 成功响应
     * { "code": 200, "data": true }
     */

    public  function  open_chance_gift(Request $request){
        $where[] =['key','BONUS_POOL_TYPE'];
        $param =[
            'value'=>2
        ];
        app('repo_config')->saveConfig($where,$param);
        return Response::sendData(true);
    }

    /**
     * @api {post} /boss/boss_this_replace    boss本期奖池替换
     * @apiVersion 0.1.0
     * @apiName boss本期奖池替换
     * @apiGroup 游戏管理
     * @apiParam {number} type  奖池类型：1一连 2十连 3百连 4特殊奖池，必传
     * @apiSuccessExample 成功响应
     * { "code": 200, "data": true }
     */
    public function  boss_this_replace(Request $request){
        //参数校验
        $v = app('validator')->make(
            $request->all(),
            [
                'type' => 'required|in:1,2,3,4',
            ]
        );
        if ($v->fails()) throw new BasicException(10001);
        $type =$request->input('type');
         app('repo_virus_this_prize')->delPoolType($type);
         $next_list = app('repo_virus_next_prize')->getPoolType($type);
         if ($next_list){
           app('repo_virus_this_prize')->addAllGift($next_list);
         }
         return Response::sendData(true);
    }


    /**
     * @api {post} /boss/get_chance_list  概率奖池列表
     * @apiVersion 0.1.0
     * @apiName 概率奖池列表
     * @apiGroup 游戏管理
     * @apiParam {number} type  1一连 2十连 3百连 4特殊奖池，必传
     * @apiSuccessExample 成功响应
        {
            "code": 200,
            "data": {
                "theory_times(理论次数)": "100000",
                "theory_input（理论投入金币数）": 20000000,
                "theory_output（理论产出金币数）": 20000282,
                "theory_ratio（理论产出比）": 1,
                "input_all_gold（加库存投入金币）": 29381800,
                "output_all_gold（加库存产出金币）": 34624678,
                "real_output_radio（加库存产出比）": 0.8486,
                "total_count_real（实际总次数）": "146909",
                "total_real（实际总投入金币）": 29381800,
                "output_real（实际总产出金币）": "34624678.00",
                "ratio_real（实际产出比）": 0.8486,
                "pool_type_name（抽奖奖池名称）": "当前为数量奖池",
                "pool_type（抽奖奖池类型：1 数量奖池 2 概率奖池）": "1",
                "type（奖池类型：1一连 2十连 3百连 4特殊奖池）": "3",
                "pot_name（奖池名称）": "100连奖池",
                "list（数据列表）": [
                    {
                    "id（主键id）": 35,
                    "initial_weight（初始权重）": 2,
                    "type（奖池类型）": 3,
                    "percent（奖品血量百分比）": "1",
                    "gift_id（奖品id）": 168,
                    "initial_chance（初始权重百分比，显示的时候拼接上百分号）": 0.002,
                    "revise_weight（修正权重）": 0,
                    "revise_chance（修正权重百分比，显示的时候拼接上百分号）": 0,
                    "win_prize_num（中奖个数）": "3",
                    "win_prize_gold（中奖金币数量）": "1560000.00",
                    "real_chance（实际概率,显示的时候拼接上百分号）": 0.002,
                    "gift_name（奖品名字）": "浪漫小镇",
                    "picture（礼物图片）": "http://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/admin_images/5e90357a7a97a.png",
                    "price（礼物价格）": 520000
                    }
                ]
            }
        }
     */

    public function  get_chance_list(Request $request){
        //参数校验
        $v = app('validator')->make(
            $request->all(),
            [
                'type' => 'required|in:1,2,3,4',
            ]
        );
        if ($v->fails()) throw new BasicException(10001);
        $type =$request->input('type');
        $list = app('repo_virus_chance_prize')->getChancePrizeList($type);
        $revise_weights =json_decode(Redis::get('revise_weights'.$type),true);
        if ($revise_weights){
            //获取所有修正权重的累加和
            $all_revise_weight = array_column($revise_weights,'revise_weight','id');
            $sum_revise_chance = array_sum($all_revise_weight);
        }else{
            $sum_revise_chance =0;
        }
        $sum_initial_chance=app('repo_virus_chance_prize')->totalInitialWeight($type);
        $theory_output =0;
        if ($list){
            foreach ($list as  $ky=>&$vl){
                $theory_output += ($vl['gift']['price']*$vl['initial_weight']);
                if ($sum_initial_chance!=0){
                    $initial_chance =round($vl['initial_weight']/$sum_initial_chance,5) *100;
                }else{
                    $initial_chance =0;
                }
                $vl['initial_chance'] =$initial_chance;

                if ($sum_revise_chance ==0){
                    $revise_chance =0;
                    $vl['revise_weight'] =0;
                }else{
                    if (isset($all_revise_weight[$vl['id']])){
                        $revise_chance =round($all_revise_weight[$vl['id']]/$sum_revise_chance,5) *100;
                        $vl['revise_weight'] =$all_revise_weight[$vl['id']];
                    }else{
                        $revise_chance =0;
                        $vl['revise_weight'] =0;
                    }
                }
                $vl['revise_chance'] =$revise_chance;
                $win_prize_num= app('repo_virus_win_prize_detail')->totalNumber($type,$vl['gift_id']);
                $win_prize_gold= app('repo_virus_win_prize_detail')->totalGold($type,$vl['gift_id']);
                //该分类下该奖品的中奖个数
                $vl['win_prize_num'] =$win_prize_num;
                //该分类下该奖品的中奖金币数
                $vl['win_prize_gold'] =$win_prize_gold;
                //该分类所有中奖个数
                $win_prize_all= app('repo_virus_win_prize_detail')->totalTypeNumber($type);
                //实际概率= 该分类下该奖品的中奖个数/该分类所有奖品中奖个数
                if ($win_prize_all !=0){
                    $real_chance = round($win_prize_num/$win_prize_all,5)*100;
                }else{
                    $real_chance =0;
                }
                $vl['real_chance'] =$real_chance;
                $vl['gift_name'] =$vl['gift']['name'];
                $vl['picture'] =$vl['gift']['picture'];
                $vl['price'] =$vl['gift']['price'];
                unset($vl['gift']);
            }
        }
        //预设投入值
        $sum_initial_chance_default =$sum_initial_chance;
        $default_input_value = $sum_initial_chance_default*200;
        //预设产出值
        $preset_output_value = $theory_output;
        $attack_boss= app('repo_virus_boss')->getBossDetail();
        if (!$attack_boss){
            $attack_boss_money =1;
        }else{
            $attack_boss_money = $attack_boss['attack_price'];
        }
        //投入金币数量
        $input_all_gold = app('repo_virus_price')->allTotalNumber();
        $input_real_all_gold = $input_all_gold*200* $attack_boss_money;
        $input_all_gold = $input_real_all_gold+$default_input_value;
        //产出金币数量
        $output_all_gold = app('repo_virus_price')->allTotalGold();
        $output_real_all_gold = $output_all_gold;
        $output_all_gold = $output_real_all_gold+$preset_output_value;
        //如果是初始值得两倍则减掉初始值
        for ($x=0; $x<=99999999; $x++) {
            if ($input_all_gold >(2*$default_input_value) && $output_all_gold>(2*$preset_output_value)){
                $input_all_gold = $input_all_gold -$default_input_value;
                $output_all_gold = $output_all_gold -$preset_output_value;
            }else{
                break;
            }
        }
        if ($output_all_gold !=0){
            $real_output_radio = round($input_all_gold/$output_all_gold,4);
        }else{
            $real_output_radio =0;
        }

        $total_count_real = app('repo_virus_price')->allTotalNumber();
        if ($output_real_all_gold !=0){
            $ratio_real = round($input_real_all_gold/$output_real_all_gold,4);
        }else{
            $ratio_real =0;
        }
        if ($theory_output!=0){
            $theory_ratio =round($sum_initial_chance*200/$theory_output,4);
        }else{
            $theory_ratio =0;
        }

        $pool_type= app('repo_config')->queryConfig('BONUS_POOL_TYPE');
        if ($pool_type->value==1){
            $pool_type_name ='当前为数量奖池';
        }else{
            $pool_type_name ='当前为概率奖池';
        }

        $pool_user_id = app('model_config')->where('key', 'POOL_USER')->value('value');
        $pool_user = app('model_user_data')->where(['user_id' => $pool_user_id])->select('nickname', 'user_code')->first();

        $data = [
            //理论值
            'theory_times'=>$sum_initial_chance,
            'theory_input'=>$sum_initial_chance*200,
            'theory_output'=>$theory_output,
            'theory_ratio'=>$theory_ratio,
            //加库存值
            'input_all_gold'=>$input_all_gold,
            'output_all_gold'=>$output_all_gold,
            'real_output_radio'=>$real_output_radio,
            //实际值
            'total_count_real'=>$total_count_real,
            'total_real'=>$input_real_all_gold,
            'output_real'=>$output_real_all_gold,
            'ratio_real'=>$ratio_real,
            //数据列表和参数
            'pool_type_name'=>$pool_type_name,
            'pool_type'=>$pool_type->value,
            'type'=>$this->type,
            'pot_name'=>$this->pot_name,
            'pool_user' => $pool_user,
            'list'=>$list,
        ];
        return  Response::sendData($data);
    }

    /**
     * @api {post} /boss/boss_win_gift_list    boss大作战中奖记录
     * @apiVersion 0.1.0
     * @apiName boss大作战中奖记录
     * @apiGroup 游戏管理
     * @apiParam {string} keyword  用户编号或者用户昵称，非必传
     * @apiParam {number} gift_id  礼物id，非必传
     * @apiParam {string} start_time  开始时间，非必传
     * @apiParam {string} end_time  结束时间，非必传
     * @apiParam {number} page  页数，非必传
     * @apiParam {number} perPage  每页数量，非必传
     * @apiSuccessExample 成功响应
        {
            "code": 200,
            "data": {
                "list": [
                    {
                    "id(序号)": 187635,
                    "number（礼物数量）": 1,
                    "gift_id（礼物id）": 145,
                    "add_time（中奖时间）": "2020-08-20 10:57:19",
                    "user_code（用户编号）": 439433,
                    "nickname（用户昵称）": "-封丘-",
                    "gift_name（礼物名字）": "比心",
                    "picture（礼物图片）": "http://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/admin_images/5e3bb2b309012.png"
                    }
                ],
                "meta": {
                    "page": 1,
                    "limit": 20,
                    "next": null,
                    "total": 1
                }
            }
        }
     */

    public  function  boss_win_gift_list(Request $request){
        //参数校验
        $v = app('validator')->make(
            $request->all(),
            [
                'keyword' => 'filled',
                'gift_id' => 'filled|numeric',
                'page' => 'filled|numeric',
                'perPage' => 'filled|numeric',
                'start_time' => 'filled|date_format:"Y-m-d H:i:s"',
                'end_time' => 'filled|date_format:"Y-m-d H:i:s"',
            ],
            [
                'keyword.filled' => '用户id|昵称不能为空',
            ]);
        if ($v->fails()) throw new BasicException(10001, $v->errors()->first());
        $perPage =$request->input('perPage',20);
        $page =$request->input('page',1);
        $keyword =$request->input('keyword','');
        $gift_id =$request->input('gift_id','');
        if ($gift_id){
            $where[] =['gift_id',$gift_id];
        }
        $start_time =$request->input('start_time');
        $end_time =$request->input('end_time');
        $time = CommonService::transTime($start_time,$end_time);
        $search_time = [$time['start_at'],$time['end_at']];
        $where[] =[function($query) use ($search_time){
            $query->whereBetween('add_time',$search_time);
        }];
        $list =app('repo_virus_win_prize_detail')->winGiftList($where,$keyword,$page,$perPage);
        if ($list){
            foreach ($list as $key=>&$value){
                $value->user_code =$value->user_data->user_code;
                $value->nickname =$value->user_data->nickname;
                $value->gift_name =$value->gift->name;
                $value->picture =$value->gift->picture;
                $value->add_time =date('Y-m-d H:i:s',$value->add_time);
                unset($value->user_data);
                unset($value->gift);
                unset($value->user_id);
            }
        }
        return Response::sendList($list);
    }




    /**
     * @api {get} /boss/boss_win_gift_export    boss导出中奖记录
     * @apiVersion 0.1.0
     * @apiName boss导出中奖记录
     * @apiGroup 游戏管理
     * @apiParam {string} keyword  用户编号或者用户昵称，非必传
     * @apiParam {number} gift_id  礼物id，非必传
     * @apiParam {string} start_time  开始时间，非必传
     * @apiParam {string} end_time  结束时间，非必传
     * @apiParam {number} page  页数，非必传
     * @apiParam {number} perPage  每页数量，非必传
     * @apiSuccessExample 成功响应
     * 导出一个xls格式的中奖数据表
     */
    public  function  boss_win_gift_export(Request $request){
        //参数校验
        $v = app('validator')->make(
            $request->all(),
            [
                'keyword' => 'filled',
                'gift_id' => 'filled|numeric',
                'page' => 'filled|numeric',
                'perPage' => 'filled|numeric',
                'start_time' => 'filled|date_format:"Y-m-d H:i:s"',
                'end_time' => 'filled|date_format:"Y-m-d H:i:s"',
            ]
        );
        if ($v->fails()) throw new BasicException(10001);
        $perPage =$request->input('perPage',20);
        $page =$request->input('page',1);
        $keyword =$request->input('keyword','');
        $gift_id =$request->input('gift_id','');
        if ($gift_id){
            $where[] =['gift_id',$gift_id];
        }
        $start_time =$request->input('start_time');
        $end_time =$request->input('end_time');
        $time = CommonService::transTime($start_time,$end_time);
        $search_time = [$time['start_at'],$time['end_at']];
        $where[] =[function($query) use ($search_time){
            $query->whereBetween('add_time',$search_time);
        }];
        $list =app('repo_virus_win_prize_detail')->winGiftList($where,$keyword,$page,$perPage);
        if ($list){
            foreach ($list as $key=>&$value){
                $value->user_code =$value->user_data->user_code;
                $value->nickname =$value->user_data->nickname;
                $value->gift_name =$value->gift->name;
                $value->picture =$value->gift->picture;
                $value->add_time =date('Y-m-d H:i:s',$value->add_time);
                unset($value->user_data);
                unset($value->gift);
                unset($value->user_id);
                unset($value->gift_id);
                unset($value->picture);
            }
            $list = $list->toArray();
        }
        if (isset($list['data'])){
            $list = $list['data'];
            $headings = [
                '序号',
                '奖品数量',
                '中奖时间',
                '用户编号',
                '用户昵称',
                '奖品名称',
            ];
            return app('repo_export')->export(3, $request->all(), $headings, $list);
        }
    }

    /**
     * @api {Get} /boss/bloodVolumePool boss血量奖池
     * @apiGroup 补充接口-病毒大作战
     *
     * @apiParam {Int} boss_pool_type 奖池类型，6：本期奖池(默认)；7：下期奖池
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": {
    "current_page": 1,
    "data": [
    {
    "id": 141,
    "gift_id": 163, 礼物id
    "number": 10, 数量
    "gift_name": "告白花束", 礼物名称
    "price": 52000, 价格，单位：元
    "picture": "http://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/admin_images/5e66f7a7460ba.png", 礼物图片
    "special": "http://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/admin_images/5e66f7aee2f7f.svga",
    "gift_rank": "紫色" 礼物等级
    }
    ],
    "first_page_url": "http://local.qipaoadmin/boss/bloodVolumePool?page=1",
    "from": 1,
    "last_page": 1,
    "last_page_url": "http://local.qipaoadmin/boss/bloodVolumePool?page=1",
    "next_page_url": null,
    "path": "http://local.qipaoadmin/boss/bloodVolumePool",
    "per_page": 20,
    "prev_page_url": null,
    "to": 7,
    "total": 7
    }
    }
     */
    public function bloodVolumePool(Request $request)
    {
        $type = $request->boss_pool_type ?: 6;

        if ($type == 6) {
            $model = app('model_virus_boss_blood_prize');
        } else if ($type == 7) {
            $model = app('model_virus_boss_blood_next_prize');
        } else {
            throw new BasicException(10001);
        }
        return Response::sendData($model->getWinJackpotList());
    }

    /**
     * @api {Post} /boss/bloodVolumePoolGiftAdd 新增boss血量奖池礼物
     * @apiGroup 补充接口-病毒大作战
     *
     * @apiParam {Int} boss_pool_type 奖池类型，6：本期奖池(默认)；7：下期奖池
     * @apiParam {Int} gift_id 礼物id
     * @apiParam {Int} number 礼物数量
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "message": "添加成功"
    }
     */
    public function bloodVolumePoolGiftAdd(Request $request)
    {
        $type = $request->boss_pool_type ?: 6;
        $giftId = $request->gift_id;
        $number = $request->number;

        $model = $this->paramVerify($giftId, $number, $type);

        $res = $model->insert([
            'gift_id' => $giftId,
            'number' => $number,
            'type' => 0,
        ]);
        if ($res) {
            return Response::sendData([]);
        } else {
            throw new BasicException(0, '添加失败');
        }
    }

    /**
     * @api {Put} /boss/bloodVolumePoolGiftEdit 编辑boss血量奖池礼物
     * @apiGroup 补充接口-病毒大作战
     *
     * @apiParam {Int} boss_pool_type 奖池类型，6：本期奖池(默认)；7：下期奖池
     * @apiParam {Int} id 主键id
     * @apiParam {Int} gift_id 礼物id
     * @apiParam {Int} number 礼物数量
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "message": "编辑成功"
    }
     */
    public function bloodVolumePoolGiftEdit(Request $request)
    {
        $type = $request->boss_pool_type ?: 6;
        $id = $request->id;
        $giftId = $request->gift_id;
        $number = $request->number;

        $model = $this->paramVerify($giftId, $number, $type, $id);

        $res = $model->where('id', $id)->update([
            'gift_id' => $giftId,
            'number' => $number,
        ]);
        if ($res) {
            return Response::sendData([]);
        } else {
            throw new BasicException(0, '编辑失败');
        }
    }

    private function paramVerify($giftId, $number, $type, $id = 0)
    {
        if (empty($giftId)) {
            throw new BasicException(0, '请选择礼物');
        }
        $gift = app('model_gift')->where('type', 6)->where('id', $giftId)->first();
        if (empty($gift)) {
            throw new BasicException(10001);
        }
        if (empty($number) || !is_numeric($number) || $number < 0) {
            throw new BasicException(0, '数量有误');
        }

        if ($type == 6) {
            $model = app('model_virus_boss_blood_prize');
        } else if ($type == 7) {
            $model = app('model_virus_boss_blood_next_prize');
        } else {
            throw new BasicException(10001);
        }

        if ($id !== 0) {
            $exist = $model->select('id')->where('id', $id)->first();
            if (!$exist) {
                throw new BasicException(10001);
            }
        }

        $where = [['gift_id', '=', $giftId], ['type', '=', 0]];
        if ($id) {
            $where[] = ['id', '<>', $id];
        }
        $exist = $model->where($where)->first();
        if ($exist) {
            throw new BasicException(0, '礼物已经存在');
        }
        return $model;
    }

    /**
     * @api {Delete} /boss/bloodVolumePoolGiftDel 删除boss血量奖池礼物
     * @apiGroup 补充接口-病毒大作战
     *
     * @apiParam {Int} boss_pool_type 奖池类型，6：本期奖池(默认)；7：下期奖池
     * @apiParam {Int} ids 主键id，多个用英文逗号连接
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "message": "删除成功"
    }
     */
    public function bloodVolumePoolGiftDel(Request $request)
    {
        $type = $request->boss_pool_type ?: 6;
        $ids = $request->ids;

        if ($type == 6) {
            $model = app('model_virus_boss_blood_prize');
        } else if ($type == 7) {
            $model = app('model_virus_boss_blood_next_prize');
        } else {
            throw new BasicException(10001);
        }

        $ids = explode(',', $ids);
        DB::beginTransaction();
        try {
            foreach ($ids as $id) {
                if ($id) {
                    $exist = $model->select('id')->where('id', $id)->first();
                    if (!$exist) {
                        throw new BasicException(10001);
                    }
                    $model->where('id', $id)->delete();
                }
            }
            DB::commit();
            return Response::sendData([]);
        } catch (\Exception $e) {
            DB::rollBack();
            throw new BasicException(0, $e->getMessage());
        }
    }

}
